package Algorithm;

public class KMP {
    public int[] nextArray(char[] pattern) {
        int[] lps = new int[pattern.length];
        int j = 0;
        for(int i = 1; i < pattern.length;) {
            if(pattern[i] == pattern[j]) {
                lps[i] = j + 1;
                j++;
                i++;
            } else {
                if(j != 0) {
                    j = lps[j-1];
                } else {
                    lps[i] = 0;
                    i++;
                }
            }
        }
        return lps;
    }

    public boolean kmp(char[] text, char[] pattern) {
        int[] lps = nextArray(pattern);
        int i = 0;
        int j = 0;
        for(i = 0; i < text.length;) {
            if(text[i] == pattern[j]) {
                i++;
                j++;
            } else {
                if(j != 0) {
                    j = lps[j-1];
                } else {
                    i++;
                }
            }
        }
        if(j == pattern.length) {
            return true;
        }
        return false;
    }

    public static void main(String[] args) {
        String str = "abcdegsjoiajabcdabcdy";
        String subString = "abcdabcdy";
        KMP k = new KMP();
        boolean res = k.kmp(str.toCharArray(), subString.toCharArray());
        System.out.println(res);
    }
}
